package com.ruoyi.xiaoshou.service.impl;

import com.ruoyi.IndexDtoByTwo;
import com.ruoyi.basedata.api.RemoteCustomerService;
import com.ruoyi.basedata.domain.CustomerUtil;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.domain.basedata.Customer;
import com.ruoyi.system.api.domain.store.StockIn;
import com.ruoyi.xiaoshou.domain.*;
import com.ruoyi.xiaoshou.dto.SaleBackDto;
import com.ruoyi.xiaoshou.mapper.SaleBackDetailMapper;
import com.ruoyi.xiaoshou.mapper.SaleBackMapper;
import com.ruoyi.xiaoshou.mapper.SaleBackRequestDetailMapper;
import com.ruoyi.xiaoshou.mapper.SaleBackRequestMapper;
import com.ruoyi.xiaoshou.service.ISaleBackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.UUID;

/**
 * 销售退货单Service业务层处理
 *
 * @author lmj
 * @date 2024-10-29
 */
@Service
@Slf4j
@Transactional
public class SaleBackServiceImpl implements ISaleBackService {
    @Autowired
    private SaleBackMapper saleBackMapper;
    @Autowired
    private SaleBackDetailMapper saleBackDetailMapper;
    @Autowired
    private SaleBackRequestMapper saleBackRequestMapper;
    @Autowired
    private SaleBackRequestDetailMapper saleBackRequestDetailMapper;
    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Override
    public AjaxResult addSaleBack(int saleBackRequestId, String userId) {
        log.info("SaleBackServiceImpl addSaleBack params:{},{}", saleBackRequestId, userId);
        //先根据申请id查询申请单，然后根据申请单编号查询申请详情列表，
        SaleBackRequest saleBackRequest = saleBackRequestMapper.selectSaleBackRequestById(saleBackRequestId);
        String saleBackRequestCode = saleBackRequest.getSaleBackRequestCode();
        SaleBackRequestDetail saleBackRequestDetail = new SaleBackRequestDetail();
        saleBackRequestDetail.setSaleBackRequestCode(saleBackRequestCode);
        List<SaleBackRequestDetail> saleBackRequestDetails = saleBackRequestDetailMapper.selectSaleBackRequestDetailList(saleBackRequestDetail);
        if (!saleBackRequestDetails.isEmpty()) {
            //然后添加退货订单，添加订单详情
            SaleBack saleBack = new SaleBack();
            String saleBackCode = "THDD" + UUID.randomUUID().toString();
            saleBack.setSaleBackCode(saleBackCode);
            saleBack.setSaleBackRequestCode(saleBackRequestCode);
            saleBack.setTotal(saleBackRequest.getTotal());
            saleBack.setCreateBy(userId);
            boolean flag = saleBackMapper.insertSaleBack(saleBack) > 0;
            if (!flag) {
                log.error("addSaleBack fail");
                throw new RuntimeException("添加销售退货订单失败");
            }
            for (SaleBackRequestDetail saleBackRequestDetail1 : saleBackRequestDetails) {
                SaleBackDetail saleBackDetail = new SaleBackDetail();
                saleBackDetail.setSaleBackCode(saleBackCode);
                saleBackDetail.setProCode(saleBackRequestDetail1.getProCode());
                saleBackDetail.setProNum(saleBackRequestDetail1.getProNum());
                saleBackDetail.setPrice(saleBackRequestDetail1.getPrice());
                saleBackDetail.setCreateBy(userId);
                boolean flag1 = saleBackDetailMapper.insertSaleBackDetail(saleBackDetail) > 0;
                if (!flag1) {
                    log.error("insertSaleBackDetail fail");
                    throw new RuntimeException("添加销售退货订单详情失败");
                }
            }
        } else {
            log.error("saleBackRequestDetails error");
            throw new RuntimeException("没有相关的退货详情");
        }
        return AjaxResult.success();
    }

    @Override
    public IndexDtoByTwo getSaleBackCountAndMoney() {
        return saleBackMapper.getSaleBackCountAndMoney();
    }

    /**
     * 查询销售退货单
     *
     * @param id 销售退货单主键
     * @return 销售退货单
     */
    @Override
    public SaleBack selectSaleBackById(Integer id) {
        return saleBackMapper.selectSaleBackById(id);
    }

    /**
     * 查询销售退货单列表
     *
     * @param saleBack 销售退货单
     * @return 销售退货单
     */
    @Override
    public List<SaleBack> selectSaleBackList(SaleBack saleBack) {
        return saleBackMapper.selectSaleBackList(saleBack);
    }

    @Override
    public List<SaleBack> noReconList(SaleBack saleBack) {
        return saleBackMapper.noReconList(saleBack);
    }
    public List<SaleBack> selectSaleBackListForReciveOrder(SaleBack saleBack) {
        return saleBackMapper.selectSaleBackListForReciveOrder(saleBack);
    }

    @Override
    public List<SaleBack> getUseList(SaleBack saleBack) {
        return saleBackMapper.getUseList(saleBack);
    }
    public List<SaleBack> getSaleBackListByOrderCodes(String[] codes) {
        List<SaleBack> saleOrderList = saleBackMapper.selectSaleBackListByOrderCodes(codes);
        return saleOrderList;
    }

    /**
     * 新增销售退货单
     *
     * @param saleBackDto 销售退货单
     * @return 结果
     */
    @Override
    public AjaxResult insertSaleBack(SaleBackDto saleBackDto) {
        log.info("SaleBackServiceImpl insertSaleBack params:{}", saleBackDto);
        SaleBack saleBack = saleBackDto.getSaleBack();
        List<SaleBackDetail> saleBackDetails = saleBackDto.getSaleBackDetailList();
        //判断编号不能重复
        SaleBack saleBack1 = new SaleBack();
        saleBack1.setSaleBackCode(saleBack.getSaleBackCode());
        int count = saleBackMapper.getSaleBackCount(saleBack1);
        if (count > 0) {
            log.error("insertSaleBack saleBackCode repeat");
            return AjaxResult.warn("订单编号重复，请修改");
        }
        //获取客户id
        R<CustomerUtil> result = remoteCustomerService.selectCustomerByName(saleBack.getCusName(), SecurityConstants.INNER);
        int cusId = result.getData().getId();
        saleBack.setCusId(cusId);
        boolean flag = saleBackMapper.insertSaleBack(saleBack) > 0;
        if (!flag) {
            log.error("insertSaleBack fail");
            throw new RuntimeException("插入销售退货订单错误");
        }
        for (SaleBackDetail saleBackDetail1 : saleBackDetails) {
            boolean flag1 = saleBackDetailMapper.insertSaleBackDetail(saleBackDetail1) > 0;
            if (!flag1) {
                log.error("insertSaleBackDetail fail");
                throw new RuntimeException("插入销售退货订单详情错误");
            }
        }
        return AjaxResult.success();
    }

    @Override
    public String refreshStatusByStockIn(StockIn stockIn) {
        log.info("SaleBackServiceImpl refreshStatusByStockIn params:{}", stockIn);
        //根据订单编号查询订单，然后加上对应字段，最后判断状态
        SaleBack saleBack = saleBackMapper.selectSaleBackByCode(stockIn.getOrderCode());
        saleBack.setInNum(saleBack.getInNum() + stockIn.getPassNum());
        saleBack.setNoPassNum(saleBack.getNoPassNum() + stockIn.getNoPassNum());
        BigDecimal realMoney = saleBack.getRealMoney().add(stockIn.getPassCost());
        saleBack.setRealMoney(realMoney);
        BigDecimal payCent = saleBack.getRealMoney().divide(saleBack.getTotal(), 2, RoundingMode.HALF_UP);
        saleBack.setPayCent(payCent);
        if (saleBack.getInNum() == 0) {
            saleBack.setStockStatus(0);
        }
        if (saleBack.getInNum() > 0) {
            saleBack.setStockStatus(1);
        }
        if (saleBack.getInNum() == 0 && saleBack.getNoPassNum() == 0) {
            saleBack.setQualitiedStatus(0);
        }
        if (saleBack.getInNum() > 0 || saleBack.getNoPassNum() > 0) {
            saleBack.setQualitiedStatus(1);
        }
        if ((saleBack.getInNum() + saleBack.getNoPassNum()) == saleBack.getTotalNum()) {
            saleBack.setStockStatus(2);
            saleBack.setQualitiedStatus(2);
        }
        boolean flag = saleBackMapper.updateSaleBack(saleBack) > 0;
        if (!flag) {
            return "500";
        }
        return "200";
    }

    /**
     * 修改销售退货单，传入saleBack和saleBackDetailList
     * 查询saleBack的原来编号，删除对应的详情，然后将在修改saleBack，加上新的详情
     *
     * @param saleBackDto 销售退货单
     * @return 结果
     */
    @Override
    public AjaxResult updateSaleBack(SaleBackDto saleBackDto) {
        log.info("SaleBackServiceImpl updateSaleBack params:{}", saleBackDto);
        SaleBack saleBack = saleBackDto.getSaleBack();
        List<SaleBackDetail> saleBackDetails = saleBackDto.getSaleBackDetailList();
        //删除详情
        SaleBack saleBack2 = saleBackMapper.selectSaleBackById(saleBack.getId());
        String saleBackCode = saleBack2.getSaleBackCode();
        boolean flag2 = saleBackDetailMapper.deleteSaleBackDetailBySaleBackCode(saleBackCode) > 0;
        if (!flag2) {
            log.error("SaleBackServiceImpl deleteSaleBackDetailBySaleBackCode error");
            throw new RuntimeException("删除退货详情错误");
        }
        //判断编号不能重复
        SaleBack saleBack1 = new SaleBack();
        saleBack1.setId(saleBack.getId());
        saleBack1.setSaleBackCode(saleBack.getSaleBackCode());
        int count = saleBackMapper.getSaleBackCount(saleBack1);
        if (count > 0) {
            log.error("updateSaleBack saleBackCode repeat");
            return AjaxResult.warn("订单编号重复，请修改");
        }
        boolean flag = saleBackMapper.updateSaleBack(saleBack) > 0;
        if (!flag) {
            log.error("updateSaleBack fail");
            throw new RuntimeException("修改销售退货订单错误");
        }
        for (SaleBackDetail saleBackDetail1 : saleBackDetails) {
            boolean flag1 = saleBackDetailMapper.insertSaleBackDetail(saleBackDetail1) > 0;
            if (!flag1) {
                log.error("updateSaleBack insertSaleBackDetail fail");
                throw new RuntimeException("修改销售退货订单详情错误");
            }
        }
        return AjaxResult.success();
    }

    public AjaxResult checkSaleBack(SaleBack saleBack) {
        log.info("SaleBackServiceImpl checkSaleBack params:{}", saleBack);
        boolean flag = saleBackMapper.updateSaleBack(saleBack) > 0;
        if (!flag) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除销售退货单
     *
     * @param ids 需要删除的销售退货单主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteSaleBackByIds(Integer[] ids) {
        log.info("SaleBackServiceImpl deleteSaleBackByIds params:{}", (Object) ids);
        //先把id对应的订单编号查询出来，然后把对应的详情删除
        for (int id : ids) {
            SaleBack saleBack = saleBackMapper.selectSaleBackById(id);
            String saleBackCode = saleBack.getSaleBackCode();
            boolean flag = saleBackDetailMapper.deleteSaleBackDetailBySaleBackCode(saleBackCode) > 0;
            if (!flag) {
                log.error("deleteSaleBack deleteSaleBackDetailBySaleBackCode fail");
                throw new RuntimeException("删除退货订单失败");
            }
            boolean flag1 = saleBackMapper.deleteSaleBackById(id) > 0;
            if (!flag1) {
                log.error("deleteSaleBack deleteSaleBackById fail");
                throw new RuntimeException("删除退货订单失败");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 删除销售退货单信息
     *
     * @param id 销售退货单主键
     * @return 结果
     */
    @Override
    public int deleteSaleBackById(Integer id) {
        return saleBackMapper.deleteSaleBackById(id);
    }

    @Override
    public int updateSaleBackyCode(SaleBack saleBack) {
        return saleBackMapper.updateSaleBack(saleBack);
    }
}
